import fs from 'fs'
import path from 'path'
import {  Request, Response } from 'express'
interface ReqData {
  author: string,
  bookname: string,
  publisher:  string,
}
interface Book{
  id: number,
  author: string,
  bookname: string,
  publisher:  string,
  createdAt: Date,
  updateAt: Date
}
interface resData {
  data: Book[],
  message: string
}
const addBook = (req:Request, res:Response) => {
  const reqData: ReqData = req.body
  if (!req.body || ! reqData.bookname) {
    res.status(400)

    res.send('提交的数据有误，请检查')
    return
  }
  fs.readFile(path.join(__dirname, './data/book.json'), (err, data) => {
    if (err) {
      res.status(500)
      res.send('服务器内部错误')
      return
    }
    const books = JSON.parse(data.toString())
    const book1: Book = {
      id: books[books.length - 1].id + 1,
      author: reqData.author,
      bookname: reqData.bookname,
      publisher: reqData.publisher,
      createdAt: new Date(),
      updateAt: new Date()
    }
    const book = {
      id: books[books.length - 1].id + 1,
      ...req.body,
      createdAt: new Date(),
      updateAt: new Date(),
    }
    books.push(book)
    fs.writeFile(path.join(__dirname, './data/book.json'), JSON.stringify(books), err => {
      if (err) {
        res.status(500)
        res.send('500')
        return
      }
      const result: resData = {
        message: '添加成功',
        data: book
      }
      res.send(JSON.stringify(result))
    })
  })
}
const delBook = (req: Request, res: Response) => {
  console.log("delBook");
}
export {
  addBook,
  delBook
}
